package com.ifcar.app.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;

import com.ifcar.app.util.BaseImageDownloader.FlushedInputStream;

public class PicUtil {

    //缓存图片存放目录
	public static String phototempDir = "/sdcard/netease/newsreader/netease_temp_pic/";
	//下载图片存放目录
	public static String photodownDir = "/sdcard/netease/newsreader/netease_down_pic/";
	//非wifi情况在图片缩略质量百分比
	public static String quality = ".50";
	/**
	 * 创建图片缓存目录
	 * @return
	 */
	public static boolean createPhotoTempFolder() {
		File file = new File(phototempDir);
		File f = new File(phototempDir+".nomedia");
		if((FileUtils.isSDCardMounted() || FileUtils.isSDCardMountedReadOnly()) && file.exists()){
			if(!f.exists() || !f.isDirectory()) {
				f.mkdir();		
			}
			return true;
		}else{
			if(FileUtils.isSDCardMounted()) {
				if(file.mkdirs()) {
					f.mkdir();
					return true;
				} else {
					return false;
				}				
			} else return false;
			
		}	
	}
	/**
	 * 3G图片缩略服务URL
	 * @param orgurl
	 * @param width
	 * @param length
	 * @return
	 */
	public static String  get3gImgurl(String orgurl,int width,int length){
		if (TextUtils.isEmpty(orgurl)) {
		    return "";
		}
		String url = StringUtil.imageResize_Url;
		if(orgurl.contains("http://")){
			url = url + orgurl.replace("http://", "")+"."+width+"x"+length+".auto.jpg";
		}else{
			url = url + orgurl+"."+width+"x"+length+".auto.jpg";
		}
		
		return url;
	}
	
	/**
	 * 在非wifi网络条件下 改造图片缩略下载URL，从而可以下载质量较低的图片，极少流量，提高速度
	 * @param url
	 * @param context
	 * @return String
	 */
	public static String getImgUrlByNetType(String url,Context context){
	    
	  String tempurl =  url;
	  
	  if(!Tools.isWifi(context) && isResizeUrl(url)){
	      tempurl = tempurl.substring(0, (tempurl.length()-9))+quality+".auto.jpg";
	  }
	  
	  return tempurl;
	}
	
	/**
	 * 判断是否为待网络缩略的图片
	 * @param url
	 * @return boolean
	 */
	public static boolean isResizeUrl(String url){
	    
	    if(null==url || "".equalsIgnoreCase(url)){
	        return false;
	    }else{
	        if(url.startsWith(StringUtil.imageResize_Url) && url.endsWith(".auto.jpg")){
	            return true;
	        }else{
	            return false;
	        }
	    }
	}
	
	/**
	 * 裁剪图片40x40
	 * @param context
	 * @param src
	 * @return
	 */
	public static Bitmap resizeBitmap(Context context, Bitmap src) {
		return resizeBitmap(context,src,40,40);
	}

	/**
	 * 处理文章正文的小图片
	 * @param context
	 * @param src
	 * @param frameW
	 * @param frameH
	 * @param result_w
	 * @param result_h
	 * @return
	 */
	public static Bitmap resizeBitmap4DetailPage(Context context, Bitmap src, final int frameW,
			final int frameH, int result_w, int result_h) {
	    
		if (src == null) {
			return null;
		}
		
		final int w = src.getWidth();// 源文件的大小
		final int h = src.getHeight();
		if (w == 0 || h == 0)
			return null;
		
		if(w==frameW && h==frameH){//如果比例相同，那么不进行缩略
		    return src;
		}else{
			
		    try{
		        float scaleWidth = ((float) frameW) / w;// 宽度缩小比例
	            float scaleHeight = ((float) frameH) / h;// 高度缩小比例
	            
	            Matrix matrix = new Matrix();// 矩阵
	            matrix.postScale(scaleWidth, scaleHeight);// 设置矩阵比例
	            
	            Bitmap resizedBitmap = Bitmap.createBitmap(src, 0, 0, w, h, matrix, true);// 直接按照矩阵的比例把源文件画入进行
	            
	            Bitmap result = cutBitmap4DetailPage(resizedBitmap, result_w, result_h);

	            if(!result.equals(resizedBitmap) && !resizedBitmap.isRecycled()){
	                resizedBitmap.recycle();
	                resizedBitmap = null;
	            }
	            
	            return result;
		    }catch(Exception ex){
		        
		    }catch(java.lang.OutOfMemoryError error){
		        
		    }
		    return src;
		}
		
	}
	
	// 获得圆角图片的方法

    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        if(bitmap == null) return null;
        
        Bitmap output = null;
        try{
            output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(output);

            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            final RectF rectF = new RectF(rect);

            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint); 
        }catch(Exception ex){
            
        }catch(java.lang.OutOfMemoryError error){
            
        }
        
        return output;

    }
	
	/**
	 * 裁切新闻正文图片
	 * @param src 原图
	 * @param w 新图的宽
	 * @param h 新图的高
	 * @return Bitmap
	 */
	public static Bitmap cutBitmap4DetailPage(Bitmap src, int w, int h) {
		try {
            if (src == null) {
            	return null;
            }
            
            int imgW = src.getWidth();
            int imgH = src.getHeight();
            
            int sx = w>=imgW?0:((imgW-w)/2);

            
            Bitmap b = Bitmap.createBitmap(src, sx, 0,  imgW > w ? w : imgW,  imgH > h ? h : imgH);
            
            return b;
        } catch (Exception e) {
           return null;
        }catch (java.lang.OutOfMemoryError error){
            return null;
        }
	}
	
	/**
	 * 按一定的比例进行裁剪
	 * @param context
	 * @param src
	 * @param frameW
	 * @param frameH
	 * @return
	 */
	public static Bitmap resizeBitmap(Context context, Bitmap src, final int frameW,
			final int frameH) {
        
        if (src == null) {
            return null;
        }
        
        final int w = src.getWidth();// 源文件的大小
        final int h = src.getHeight();
        if (w == 0 || h == 0)
            return null;
        
        if(w==frameW && h==frameH){//如果比例相同，那么不进行缩略
            return src;
        }else{
            try {
                float scaleWidth = ((float) frameW) / w;// 宽度缩小比例
                float scaleHeight = ((float) frameH) / h;// 高度缩小比例
                
                Matrix matrix = new Matrix();// 矩阵
                matrix.postScale(scaleWidth, scaleHeight);// 设置矩阵比例
                
                Bitmap resizedBitmap = Bitmap.createBitmap(src, 0, 0, w, h, matrix, true);// 直接按照矩阵的比例把源文件画入进行
                
                if(src != null && !src.isRecycled()) {
                    src.recycle();
                    src = null;
                }
                
                return resizedBitmap;
            } catch (java.lang.OutOfMemoryError e) {
               
            }
            return null;
        }
        
    }
	
	/**
	 * 对图片按w和h进行裁剪是，是否需要依据原图进行处理，
	 * @param src
	 * @param w
	 * @param h
	 * @param isAccordingOrg true，按原图处理，false 给出的w和h 等比裁剪
	 * @return
	 */
	public static Bitmap cutBitmap(Bitmap src,int w, int h,boolean isAccordingOrg){
        if(isAccordingOrg){
            return resizePicAccordingOrg(src,w,h);
        }else{
            return cutBitmap(src,w,h);
        }
    }
	
	/**
	 * 按w和h等比裁剪图片裁切图片
	 * @param src 原图
	 * @param w 新图的宽
	 * @param h 新图的高
	 * @return Bitmap
	 */
	public static Bitmap cutBitmap(Bitmap src, int w, int h) {
		return resizePic(src,w,h);
	}
	
	/**
	 * 依据原图的 长&宽 来裁剪图片
	 * @param src
	 * @param w:目标长
	 * @param h:目标宽
	 * @return
	 */
	public static Bitmap  resizePicAccordingOrg(Bitmap src, int w, int h){

        if (src == null) {
            return null;
        }
        
        int imgW = src.getWidth();
        int imgH = src.getHeight();
        
        int sx = w>=imgW?0:((imgW-w)/2);
        int sy = h>=imgH?0:((imgH-h)/2);
        
        try {
            Bitmap b = Bitmap.createBitmap(src, sx, sy, sx==0?imgW:w, sy==0?imgH:h);
            return b;
        } catch (java.lang.OutOfMemoryError error){
            return null;
        }catch (Exception e) {
            return null;
        }
    
    
	}
	
	/**
     * 按照width&height对图片进行等比缩放
     * 
     * @param src
     * @param width
     * @param height
     * @return
     */
    public static Bitmap resizePic(Bitmap src, int width, int height) {

        Bitmap bitmap = null;

        if (src == null || width == 0 || height == 0) {
            return bitmap;
        }

        try {
            final int srcW = src.getWidth();
            final int srcH = src.getHeight();
            final float sW = ((float)srcW) / width;
            final float sH = ((float)srcH) / height;
            if (sW == 1 && sH == 1) {
                // 需要的尺寸一致,直接返回
                bitmap = src;
            } else if (sW == sH) {
                // 长宽比一致
                bitmap = src;//Bitmap.createScaledBitmap(src, width, height, false);
            } else if (sW > sH) {
                int offsetX = (int)((srcW - width * sH) / 2);
                int offsetY = 0;
//                Matrix matrix = new Matrix();
//                matrix.postScale(1 / sH, 1 / sH);
//                bitmap = Bitmap.createBitmap(src, offsetX, offsetY, srcW - 2 * offsetX, srcH, matrix, false);
                bitmap = Bitmap.createBitmap(src, offsetX, offsetY, srcW - 2 * offsetX, srcH);
            } else {
                int offsetX = 0;
                int offsetY = (int)((srcH - height * sW) / 2);
//                Matrix matrix = new Matrix();
//                matrix.postScale(1 / sW, 1 / sW);
//                bitmap = Bitmap.createBitmap(src, offsetX, offsetY, srcW, srcH - 2 * offsetY, matrix, false);
                bitmap = Bitmap.createBitmap(src, offsetX, offsetY, srcW, srcH - 2 * offsetY);
            }
        } catch (Exception e) {
            if (bitmap != null) {
                bitmap.recycle();
                bitmap = null;
            }
        } catch (java.lang.OutOfMemoryError error){
            bitmap = null;
        }finally {
            if (src != null && src != bitmap) {
                src.recycle();
            }
        }
        
        return bitmap;
    }
	
	/**
	 * 根据图片url以及是否显示图片标识 来判断是否下载图片Drawable
	 * @param url
	 * @param mContext
	 * @param isshowimg
	 * @return
	 */
	public static Drawable getPicturefromUrl(String url,Context mContext,boolean isshowimg){
		Drawable d = null;
		try {
			
			if(isshowimg){
			    HttpParams httpParams = new BasicHttpParams();
                //设置连接超时和数据读取超时
                HttpConnectionParams.setConnectionTimeout(httpParams, Constant.TIMEOUT);
                HttpConnectionParams.setSoTimeout(httpParams, Constant.TIMEOUT);
                DefaultHttpClient httpClient = NeteaseHttpClient.getHttpClient(httpParams);
                Tools.setHttpClientHostProxy(httpClient, mContext);
				HttpGet request = new HttpGet(PicUtil.getImgUrlByNetType(url,mContext));
				HttpResponse response = httpClient.execute(request);
				HttpEntity  entity = response.getEntity();
	            InputStream is = entity.getContent();

				Bitmap b = BitmapFactory.decodeStream(new FlushedInputStream(is));
				d = new BitmapDrawable(b);
				is.close();
				entity.consumeContent();
			}
		
			return d;
		
		} catch(java.lang.OutOfMemoryError error){
		    return null;
		}catch (Exception e) {
			
			return null;
		}
	}
	
	/**
	 * 根据url下载图片bitmap值
	 * @param urlString
	 * @param mContext
	 * @return
	 */
	public static Bitmap getBitMapForStringURL(String urlString,Context mContext) {

		Bitmap bitmap = null;

		try {
		    HttpParams httpParams = new BasicHttpParams();
            //设置连接超时和数据读取超时
            HttpConnectionParams.setConnectionTimeout(httpParams, Constant.TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpParams, Constant.TIMEOUT);
            DefaultHttpClient httpClient = NeteaseHttpClient.getHttpClient(httpParams);
            Tools.setHttpClientHostProxy(httpClient, mContext);
			
			HttpGet request = new HttpGet(PicUtil.getImgUrlByNetType(urlString,mContext));
			HttpResponse response = httpClient.execute(request);
		    HttpEntity  entity = response.getEntity();
			InputStream is = entity.getContent();
			bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is));
			is.close();
			entity.consumeContent();
		}catch (IOException e) {
			
		}catch (java.lang.OutOfMemoryError error){
		    
		}catch (Exception e) {
            
        }
		return bitmap;
	}
	

	/**
	 * 将Bitmap改变成为Drawable
	 * @param bitmap b
	 * @return Drawable
	 */
	public static Drawable changeDrawableFromBitMap(Bitmap b){
		Drawable drawable = new BitmapDrawable(b);
		return drawable;
	}
	
	/**
	 * 批量离线下载获取图片
	 * @param url
	 * @param mContext
	 * @return
	 */
	public static boolean downloadImg4offline(String url,Context mContext){
	    
	    try {
            if (url == null || url.equals("")) {
               return false;
            }
            HttpParams httpParams = new BasicHttpParams();
            //设置连接超时和数据读取超时
            HttpConnectionParams.setConnectionTimeout(httpParams, Constant.TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpParams, Constant.TIMEOUT);
            DefaultHttpClient httpClient = NeteaseHttpClient.getHttpClient(httpParams);
            Tools.setHttpClientHostProxy(httpClient, mContext);
            StringBuilder smallurl  = new StringBuilder(url);
            smallurl.insert("http://".length(), "s.cimg.163.com/i/");
            smallurl.append(".220x220.auto.jpg");
            
            
            StringBuilder bigurl  = new StringBuilder(url);
            int screentype = Tools.getScreenMetrics(mContext);
            bigurl.insert("http://".length(), "s.cimg.163.com/i/");
            if(1==screentype){
                bigurl.append(".180x300.auto.jpg");
            }else if(2==screentype){
                bigurl.append(".220x370.auto.jpg");
            }else{
                bigurl.append(".420x740.auto.jpg");
            }
            if (!PicUtil.isLocalPicExit(smallurl.toString().substring(smallurl.toString()
                    .lastIndexOf("/") + 1, smallurl.toString().length()))) {
                HttpGet request = new HttpGet(PicUtil.getImgUrlByNetType(smallurl.toString(),mContext));
                HttpResponse response = httpClient.execute(request);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                if (is == null)
                   return false;
                else {
                  writeTempJPEGFile(new FlushedInputStream(is), 
                          smallurl.toString().substring(smallurl.toString().lastIndexOf("/")+1, smallurl.toString().length())).equals(""); 
                }
                is.close();
                entity.consumeContent();
            }
            if (!PicUtil.isLocalPicExit(bigurl.toString().substring(bigurl.toString()
                    .lastIndexOf("/") + 1, bigurl.toString().length()))) {
                HttpGet request = new HttpGet(PicUtil.getImgUrlByNetType(bigurl.toString(),mContext));
                HttpResponse response = httpClient.execute(request);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                if (is == null)
                   return false;
                else {
                  writeTempJPEGFile(new FlushedInputStream(is), 
                          bigurl.toString().substring(bigurl.toString().lastIndexOf("/")+1, bigurl.toString().length())).equals(""); 
                }
                is.close();
                entity.consumeContent();
            }
            
            return true;
         } catch (Exception e) {
            return false;
         }catch (java.lang.OutOfMemoryError error){
             return false;
         }

    
	}
	
	/**
	 * 将网络图片保存到本地
	 * @param url
	 * @return
	 */
	 public static boolean downloadImgToLocal(String url,Context mContext) {

	        try {
	            if (url == null || url.equals("")) {
	               return false;
	            }
	            HttpParams httpParams = new BasicHttpParams();
                //设置连接超时和数据读取超时
                HttpConnectionParams.setConnectionTimeout(httpParams, Constant.TIMEOUT);
                HttpConnectionParams.setSoTimeout(httpParams, Constant.TIMEOUT);
                DefaultHttpClient httpClient = NeteaseHttpClient.getHttpClient(httpParams);
                Tools.setHttpClientHostProxy(httpClient, mContext);
				HttpGet request = new HttpGet(PicUtil.getImgUrlByNetType(url,mContext));
				HttpResponse response = httpClient.execute(request);
				HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
	            if (is == null)
	               return false;
	            else {
	         	  writeTempJPEGFile(new FlushedInputStream(is), 
	         			  url.substring(url.lastIndexOf("/")+1, url.length())).equals(""); 
	            }
	            is.close();
	            entity.consumeContent();
	            return true;
	         } catch (Exception e) {
	            return false;
	         }catch (java.lang.OutOfMemoryError error){
	             return false;
	         }

	    }
	 
	 /**
	     * 将网络图片保存到本地for 离线
	     * @param url
	     * @return
	     */
	     public static long downloadImgToLocal4Offline(String url,Context mContext) {

	            try {
	                if (url == null || url.equals("")) {
	                   return -1;
	                }
	                HttpParams httpParams = new BasicHttpParams();
	                //设置连接超时和数据读取超时
	                HttpConnectionParams.setConnectionTimeout(httpParams, Constant.TIMEOUT);
	                HttpConnectionParams.setSoTimeout(httpParams, Constant.TIMEOUT);
	                DefaultHttpClient httpClient = NeteaseHttpClient.getHttpClient(httpParams);
	                Tools.setHttpClientHostProxy(httpClient, mContext);
	                HttpGet request = new HttpGet(PicUtil.getImgUrlByNetType(url,mContext));
	                HttpResponse response = httpClient.execute(request);
	                HttpEntity entity = response.getEntity();
	                InputStream is = entity.getContent();
	                long size = entity.getContentLength();
	                if (is == null)
	                   return -1;
	                else {
	                  writeTempJPEGFile(new FlushedInputStream(is), 
	                          url.substring(url.lastIndexOf("/")+1, url.length())).equals(""); 
	                }
	                is.close();
	                entity.consumeContent();
	                return size<0?0:size;
	             } catch (Exception e) {
	                return -1;
	             }catch (java.lang.OutOfMemoryError error){
	                 return -1;
	             }

	        }
    
	/**
	 * 将网络图片保存到本地
	 * @param url
	 * @return
	 */
	 public static boolean downloadImgToLocal(String path, String url,Context mContext) {
	        try {
	            if (url == null || url.equals("")) {
	               return false;
	            }
	            HttpParams httpParams = new BasicHttpParams();
                //设置连接超时和数据读取超时
                HttpConnectionParams.setConnectionTimeout(httpParams, Constant.TIMEOUT);
                HttpConnectionParams.setSoTimeout(httpParams, Constant.TIMEOUT);
                DefaultHttpClient httpClient = NeteaseHttpClient.getHttpClient(httpParams);
                Tools.setHttpClientHostProxy(httpClient, mContext);
				HttpGet request = new HttpGet(PicUtil.getImgUrlByNetType(url,mContext));
				HttpResponse response = httpClient.execute(request);
				HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
	            if (is == null)
	               return false;
	            else {
	         	  writeLocalJPEGFile(path, new FlushedInputStream(is), 
	         			  url.substring(url.lastIndexOf("/")+1, url.length())).equals(""); 
	            }
	            is.close();
	            entity.consumeContent();
	            return true;
	         } catch (Exception e) {
	            return false;
	         }catch (java.lang.OutOfMemoryError error){
	             return false;
	         }

	    }
    
	 /**
	  * 将bitmap保存为图片文件
	  * @param filename
	  * @param mBitmap
	  * @return
	  */
	 public static boolean downloadBitmap(String filename, Bitmap mBitmap){
		return saveMyBitmap(photodownDir,filename,mBitmap);
	
	}
	
	 /**
	  * 将bitmap存放在缓存文件目录下
	  * @param filename
	  * @param mBitmap
	  * @return
	  */
	public static boolean saveMyBitmap(String filename, Bitmap mBitmap){
		return saveMyBitmap(phototempDir,filename,mBitmap);
		
	}
	
	public static boolean saveMyBitmap(String path, String filename, Bitmap mBitmap){
	    
	    if(null==mBitmap) return false;
	    
		String returnfilename = "";

		if (filename.contains(".jpg"))
			returnfilename = path + filename;
		else
			returnfilename = path + filename + ".jpg";
		
		File file = new File(path);
		
		if(FileUtils.isSDCardMounted()) {
			if (!file.exists()) {
				file.mkdirs();
			}
			File f = new File(returnfilename);
			try {
				if(f.exists()){
				    
				    f.delete();
				}
				
				FileOutputStream fOut = new FileOutputStream(f);
				mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
				fOut.flush();
				fOut.close();
			} catch (Exception e) {
				e.printStackTrace();
				try {
                    if(f.exists()) f.delete();
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
				return false;
			}catch (OutOfMemoryError e) {
	            e.printStackTrace();
	            try {
                    if(f.exists()) f.delete();
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
	            return false;
	        }
	        return true;
		} else {
		    return false;
		}

	}
	
	/**
	 * 获取缓存图片文件
	 * @param filename
	 * @return
	 */
	public static String getTempJPEGFile(String filename){
		String imageName = "";
		if (filename.contains(".jpg"))
			imageName = phototempDir + filename;
		else
			imageName = phototempDir + filename + ".jpg";
		
		return imageName;
	}
	
	/**
	 * 将图片流写入文件
	 * @param path
	 * @param is
	 * @param filename
	 * @return
	 */
	public static String writeLocalJPEGFile(String path, InputStream is, String filename) {

		String returnfilename = "";

		if (filename.contains(".jpg"))
			returnfilename = path + filename;
		else
			returnfilename = path + filename + ".jpg";

		File file = new File(path);

		try {
			if(FileUtils.isSDCardMounted()) {
				if (!file.exists()) {
					if (file.mkdirs()) {

						File picfile = new File(returnfilename);

						FileOutputStream fouts = new FileOutputStream(picfile);
						byte b[] = new byte[1024];
						int i = -1;
						while ((i = is.read(b)) != -1) {

							fouts.write(b, 0, i);
						}
						fouts.flush();
						fouts.close();
						is.close();

					} else {
						returnfilename = "";
					}
				} else {
					File picfile = new File(returnfilename);

					FileOutputStream fouts = new FileOutputStream(picfile);
					byte b[] = new byte[1024];
					int i = -1;
					while ((i = is.read(b)) != -1) {

						fouts.write(b, 0, i);
					}
					fouts.flush();
					fouts.close();
					is.close();
				}
			} else returnfilename = "";

		} catch (Exception e) {
			e.printStackTrace();
			returnfilename = "";
		}
		return returnfilename;

	}
	
	/**
     * 将图片流写入缓存文件
     * @param path
     * @param is
     * @param filename
     * @return
     */
	public static String writeTempJPEGFile(InputStream is, String filename) {
	    return writeLocalJPEGFile(phototempDir,is,filename);
	}
	/**
	 * 读取头图
	 * @param picname
	 * @param def
	 * @return
	 */
    public static Bitmap readTempJPEGFile(String picname, Drawable def) {
    	return readJPEGFile(phototempDir,picname,def);
    }
    /**
     * 读取图片
     * @param picname
     * @return
     */
    public static Bitmap readTempJPEGFile(String picname) {
    	return readTempJPEGFile(picname,null);
    }
    
    public static Bitmap readLocalJPEGFile(String path, String picname) {
    	return readJPEGFile(path,picname,null);
    }
    
    public static Bitmap readJPEGFile(String path,String picname,Drawable def){
        String picpath = "";
        if(picname.contains(".jpg"))
            picpath = path + picname;
        else picpath = path + picname + ".jpg";
        
        if(FileUtils.isSDCardMounted() || FileUtils.isSDCardMountedReadOnly()) {
            return fitSizeImg(picpath);
        } else{
            if(null!=def){
                return ((BitmapDrawable)def).getBitmap();
            }else{
                return null;
            }
            
        }
    }
	
    /**
     * 判断是否是缓存本地文件
     * @param picname
     * @return boolean
     */
	public static boolean isLocalPicExit(String picname){	
    	return isLocalPicExit(phototempDir,picname);
	}
	
	 /**
     * 判断是否是本地文件
     * @param picname
     * @return boolean
     */
	public static boolean isLocalPicExit(String path, String picname){	
    	String picpath = "";
    	if(picname.contains(".jpg"))
    		picpath = path + picname;
 		else picpath = path + picname + ".jpg";
    	
		return FileUtils.isFileExit(picpath);		
	}
	
	public static String getPicName(String picname)
	{
	    String picpath = "";
        if(picname.contains(".jpg"))
            picpath = picname;
        else picpath =picname + ".jpg";
        
        return picpath; 
	}

	/**
	 * 获取头图URL
	 * @param urlString
	 * @return
	 */
	public static String getHeandBitMapURL(String urlString, Context c) {
	    int width = Tools.getScreenWidth(c);
        int height = Tools.getHeadPicHeight(width);
        String rst = urlString;
		rst = get3G_PhotoResize(urlString,width,height);
		return rst;
	}
	
	public static String get3G_PhotoResize(String url,int width,int height){
	    return get3gImgurl(url,width,height);
	}
	
	public static String getCoverUrl(String urlString,Context c){
	    HashMap<String,Integer> m = Tools.getWidth_Height(c);
	    int width = m.get("w");
	    int height = m.get("h");
	    String rst = urlString;
        rst = get3G_PhotoResize(urlString,width,height);
	    return rst;
	}

	/**
	 * 将本地文件转化为bitmap
	 * @param path
	 * @return
	 */
	public static Bitmap fitSizeImg(String path) {

		BitmapFactory.Options opt = new BitmapFactory.Options();  
		opt.inPreferredConfig = Bitmap.Config.RGB_565;   
		opt.inPurgeable = true;  
		opt.inInputShareable = true;
		File file = new File(path);
		try {
			InputStream is = new FileInputStream(file);
			Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is),null,opt);
			if (bitmap == null) {
			    if (file.exists()) {
		            file.delete();
		        }
			}
			is.close();
			return bitmap;
		}catch (OutOfMemoryError e) {
		    e.printStackTrace();
        } catch (Exception e) {
			e.printStackTrace();
		}
        if (file.exists()) {
            file.delete();
        }
		return null;
	}
	
}
